from selenium.webdriver.common.keys import Keys

from qturboframe.lib.report.log import logger
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.webdriver.remote.webelement import WebElement
from qturboframe.lib.utils.__datatime_format__ import split_time
from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.utils.CustomError.custom_error import CustomError
from qturboframe.lib.utils.CustomError.custom_exception import CustomException
from qturboframe.public_ui.base_element import BaseElement
from qturboframe.public_ui.h_ui.button import Button


class Timer(BaseElement, CheckBasic):
    """
    hui的时间控件操作

    :Attributes:
     - calendar_div: 日历控件的弹出框div元素
    """

    time_div = WebElement

    def __init__(self, element_para, father=None, timeout=5):
        super().__init__(element_para, father, timeout)
        class_list = self._element.get_attribute('class').split(' ')
        if 'h-date-picker' not in class_list:
            self._element = self._element.find_element_by_attribute(
                'xpath', './ancestor::div[@class="h-date-picker"]', timeout=self.timeout)

    def set_value(self, value):
        """
        hui时间控件赋值

        :Args:
         - value: 时间值

        :Usage:
         - timer.set_value('20:20:20')
         - timer.set_value('20:20:20 - 21:21:21')
        """
        # 数据驱动选项
        text_list = value.split(' - ')
        if len(text_list) == 1:
            self.set_value_for_single(text_list[0])
        elif len(text_list) == 2:
            self.set_value_for_range(text_list[0], text_list[1])
        else:
            raise CustomException(CustomError.Error_EQ0301900_Timer_Parameter_InCorrect, '时间参数格式不规范！')

    def set_value_for_single(self, value):
        """
        hui时间组件赋值

        :Args:
         - value: 时间值

        :Usage:
         - timer.set_value_for_single('20:20:20')
        """
        re_displaynone = 'display: none;'
        time_input = self._element.find_element_by_attribute('tag name', 'input', timeout=self.timeout)
        time_input.secure_click()
        self.time_div = self._element.exist(
            'css selector', 'div.h-select-dropdown', timeout=0.1)
        if not self.time_div:
            self.time_div = self._driver.find_element_by_attribute(
                'css selector', 'body>div.h-select-dropdown', 'style:display: block;', timeout=self.timeout)
        hour, minute, second = split_time(value)
        # 选择hour
        div_style = self.time_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_hour(hour)
        # 选择minute
        div_style = self.time_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_minute(minute)
        # 选择second
        div_style = self.time_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_second(second)
        # 确定
        div_style = self.time_div.get_attribute('style')
        if re_displaynone not in div_style:
            confirm_div = self.time_div.exist('css selector', 'div.h-picker-confirm', timeout=0.1)
            if confirm_div:
                Button({'css selector': 'button.h-btn', 'text': '确定'}, confirm_div, 0.1).click()
            else:
                time_input.send_keys(Keys.ESCAPE)

    def set_value_for_range(self, value1, value2):
        """
        hui时间范围组件赋值

        :Args:
         - value: 时间范围值

        :Usage:
         - timer.set_value_for_range('20:20:20 - 21:21:21')
        """
        re_displaynone = 'display: none;'
        time_input = self._element.find_element_by_attribute('tag name', 'input', timeout=self.timeout)
        time_input.secure_click()
        self.time_div = self._element.exist(
            'css selector', 'div.h-select-dropdown', timeout=0.1)
        if not self.time_div:
            self.time_div = self._driver.find_element_by_attribute(
                'css selector', 'body>div.h-select-dropdown', 'style:display: block;', timeout=self.timeout)
        time_div_left = self.time_div.find_element_by_attribute(
                'css selector',
                'div.h-time-picker-with-range>div.h-picker-panel-body>div.h-picker-panel-content-left',
                timeout=self.timeout)
        time_div_right = self.time_div.find_element_by_attribute(
            'css selector',
            'div.h-time-picker-with-range>div.h-picker-panel-body>div.h-picker-panel-content-right',
            timeout=self.timeout)
        hour1, minute1, second1 = split_time(value1)
        hour2, minute2, second2 = split_time(value2)
        temp_div = self.time_div
        self.time_div = time_div_left
        # 选择hour1
        div_style = temp_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_hour(hour1)
        # 选择minute1
        div_style = temp_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_minute(minute1)
        # 选择second1
        div_style = temp_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_second(second1)
        self.time_div = time_div_right
        # 选择hour2
        div_style = temp_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_hour(hour2)
        # 选择minute2
        div_style = temp_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_minute(minute2)
        # 选择second2
        div_style = temp_div.get_attribute('style')
        if re_displaynone not in div_style:
            self.__set_second(second2)
        # 确定
        div_style = temp_div.get_attribute('style')
        if re_displaynone not in div_style:
            confirm_div = temp_div.exist('css selector', 'div.h-picker-confirm', timeout=0.1)
            if confirm_div:
                Button({'css selector': 'button.h-btn', 'text': '确定'}, confirm_div, 0.1).click()
            else:
                time_input.send_keys(Keys.ESCAPE)

    def __set_hour(self, hour):
        re_displaynone = 'display: none;'
        head_div = self.time_div.find_elements_by_attribute(
            'css selector', 'div.h-time-picker-cells>div.h-time-picker-cells-list', timeout=self.timeout)[0]
        div_style = head_div.get_attribute('style')
        if re_displaynone not in div_style:
            hour_li = head_div.find_elements_by_attribute(
                    'css selector', 'ul.h-time-picker-cells-ul>li.h-time-picker-cells-cell',
                timeout=self.timeout)[int(hour)]
            hour_li.focus()
            hour_li.secure_click()

    def __set_minute(self, minute):
        re_displaynone = 'display: none;'
        head_div = self.time_div.find_elements_by_attribute(
            'css selector', 'div.h-time-picker-cells>div.h-time-picker-cells-list', timeout=self.timeout)[1]
        div_style = head_div.get_attribute('style')
        if re_displaynone not in div_style:
            minute_li = head_div.find_elements_by_attribute(
                'css selector', 'ul.h-time-picker-cells-ul>li.h-time-picker-cells-cell',
                timeout=self.timeout)[int(minute)]
            minute_li.focus()
            minute_li.secure_click()

    def __set_second(self, second):
        re_displaynone = 'display: none;'
        head_div = self.time_div.find_elements_by_attribute(
            'css selector', 'div.h-time-picker-cells>div.h-time-picker-cells-list', timeout=self.timeout)[2]
        div_style = head_div.get_attribute('style')
        if re_displaynone not in div_style:
            second_li = head_div.find_elements_by_attribute(
                'css selector', 'ul.h-time-picker-cells-ul>li.h-time-picker-cells-cell',
                timeout=self.timeout)[int(second)]
            second_li.focus()
            second_li.secure_click()

    def clear(self):
        """
        hui时间控件值清除选项值

        :Example:
         - 例: timer.clear()
        """
        self._element.move_to()
        if self._element.exist('css selector', 'div.h-select-selection>i.h-icon-close',
                     timeout=self.timeout):
            self._element.find_element_by_attribute(
                'css selector', 'div.h-date-picker-editor>i.h-icon-close',
                timeout=self.timeout).secure_click()
        else:
            raise SeleniumError(CustomError.Error_EQ0301901_Timer_No_Control,'没有清除按钮，无法删除！')

    def is_default(self, value):
        """
        检查hui时间控件默认值

        :Args:
         - value: 待检查的选项值

        :Returns:
            匹配返回True，否则返回False

        :Example:
         - 例: timer.is_default('12:10:08')
        """
        inputele = self._element.find_element_by_attribute('tag name', 'input', timeout=self.timeout)
        inputele.focus()
        if inputele.get_attribute('value'):
            text = inputele.get_attribute('value')
        elif inputele.get_attribute('placeholder'):
            text = inputele.get_attribute('placeholder')
        elif inputele.get_attribute('defaultValue'):
            text = inputele.get_attribute('defaultValue')
        else:
            text = ''
        if text:
            if text == value:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        else:
            logger.error('没有默认值！')
            return False

    def is_nonnull(self):
        '''
        检查hui时间控件是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: timer.is_nonnull()
        '''
        self._element.focus()
        form_item = self._element.find_element_by_attribute(
            'xpath', './ancestor::div[contains(@class, "h-form-item-content")]/'
                     'parent::div[contains(@class, "h-form-item")]', timeout=self.timeout)
        item_class_list = form_item.get_attribute('class').split(' ')
        if 'h-form-item-required' in item_class_list:
            return True
        else:
            return False

    def check_default(self, value):
        '''
        校验hui时间控件默认值

        :Args:
         - value: 待检查的选项值

        :Raises:
            SeleniumError: 日历控件默认值校验不通过

        :Example:
         - 例: timer.check_default('08:10:12')
        '''
        if not self.is_default(value):
            raise SeleniumError(CustomError.Error_EQ0301902_Timer_Verify_Fail,'日历控件默认值校验不通过！')

    def check_nonull(self):
        '''
        校验hui时间控件是否非空

        :Raises:
            SeleniumError: 日历控件非空校验不通过

        :Example:
         - 例: timer.check_nonull()
        '''
        if not self.is_nonnull():
            raise SeleniumError(CustomError.Error_EQ0301902_Timer_Verify_Fail,'日历控件非空校验不通过！')